<template>
	<view class="add-observe">
		<view class="header">
			<rf-navbar title="创建观察记录" src="../../static/images/observe/add-observe-bg_top.png"
				@click="onBack"></rf-navbar>
			<image class="bg-bottom" :style="{top:navBarHeight}"
				src="../../static/images/observe/add-observe-bg_bottom.png" mode="widthFix"></image>
			<!-- <image class="bg" src="../../static/images/observe/add-observe-bg.png" /> -->
			<!-- <view class="icon inline ml40" @click="Back">
				<u-icon name="arrow-left" bold color="#000000"></u-icon>
			</view>
			<view class="f32 bold title">创建观察记录</view> -->
		</view>
		<view class="body">
			<view class="title" style="margin-top: 70rpx;">观察实录</view>
			<view class="observe-memoir-input mt20">
				<u--textarea style="white-space: pre-wrap;" v-model="form.content"
					placeholder="请输入您观察到的孩子行为（温馨提示：\n您可以点击键盘下方的麦克风按钮用语音输入）" autoHeight maxlength="-1"
					:confirmType="done"></u--textarea>
			</view>
			<view class="observe-images" style="margin-top: 40rpx; margin-left: -12px;margin-right: -12px;">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					uploadIcon="plus" :maxCount="maxCount" :capture="['album']" :accept="mediaType">
				</u-upload>
			</view>

			<view class="observe-child observe-details-list flex" @click="handleObserveChild">
				<image class="icon icon-child"></image>
				<span class="text f28">观察的孩子</span>
				<view class="headImg" v-if="childList && childList.length > 0">
					<image class="image" :style="{display:index>4 ? 'none':'flex'}" :src="item.headSculpture"
						v-for="(item,index) in childList" :key="index" mode="aspectFill">
					</image>
				</view>
				<image class="icon ml-auto icon-arrow" />
			</view>
			<view class="observe-locations observe-details-list flex" @click="handleObserveLocations">
				<image class="icon icon-location" />
				<span class="text f28">观察的地点</span>
				<span class="ml-auto f28"
					style="flex: 1; text-align: end;  margin-right: 10rpx;">{{ form.location }}</span>
				<image class="icon ml-auto icon-arrow" />
			</view>
			<view class="observe-link observe-details-list flex" @click="handleObserveLink">
				<image class="icon icon-step" />
				<span class="text f28">观察的环节</span>
				<span class="ml-auto f28" style="flex: 1; text-align: end; margin-right: 10rpx;">{{ form.link }}</span>
				<image class="icon ml-auto icon-arrow" />
			</view>

			<!-- <view class="create-wrap">
				<view class="observe-assistant" @click="assistantShowOpen">
					<view style="display: flex; justify-content: center; align-items: center;">
						<image class="icon icon-assistant" />
						<text style="display: block; margin-left: 8px;font-size: 32rpx;">AI生成观察分析</text>
					</view>
				</view>
				<view class="save-btn">
					<u-button style="font-size: 32rpx;" text="保存观察" @click="handleSave"></u-button>
				</view>
			</view> -->
			<rf-submit cancelText="AI生成观察分析" confirmText="保存" @handleUseAi="assistantShowOpen"
				@handleSave="handleSave"></rf-submit>

			<view class="title">观察分析与举措</view>
			<!-- <view style="margin-left: 10rpx; display: flex;align-items: flex-start;" v-if="form.status==1">
				<view style="padding: 10rpx;">
					<image src="../../static/icons/warn.png" style="width: 28rpx; height: 28rpx;"></image>
				</view>
				<view class="">请酌情参考超小助的分析结果，根据您对孩子的了解进行相应修改。</view>
			</view> -->
			<view class="observe-analyze-measure-input mt20">
				<u--textarea v-model="form.aiAnalysis" :placeholder="placeholder" autoHeight maxlength="-1"
					:confirmType="done"></u--textarea>
			</view>




		</view>
		<rf-loading :loading="aiAssistant" @click="onclickHide" title="返回首页等待"></rf-loading>
		<!-- 填写观察实录提醒 -->
		<rf-toast :show="toast1" :isSus="false" :title="errMsg" @click="toast1 = false"></rf-toast>
		<!-- 创建观察成功提醒 -->
		<rf-toast :show="savePopupShow" :isSus="isSus" :title="isSus ? '观察已提交' : '创建失败'"
			@click="savePopupShow = false"></rf-toast>

		<!-- ai 分析选项 -->
		<view class="assistant-popup" v-if="assistantPopupShow">
			<u-popup :safeAreaInsetBottom="false" :show="assistantPopupShow" mode="center"
				@close="assistantPopupShow = false">
				<view style="margin-bottom: -10px;">
					<image class="assistant-icon" src="../../static/images/observe/assistant-icon.png"></image>
					<view class="title f32 bold inline">超级小助教</view>
					<view class="select-cnt">
						<view style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;">
							<u-radio-group v-model="assistant[0].value" placement="column" @change="handleAssistant">
								<u-radio :customStyle="{marginBottom: '20rpx'}" style="font-size: 8px;" key="0"
									name="Additional.Items.WithGuidebook" shape="circle" activeColor="#58C866"
									inactiveColor="#E3E6E9" labelSize="14px" size="16">
									<view>请结合《指南》<text
											style="color: #58C866;text-decoration: underline; text-decoration-color: #58C866;"
											@click="assistantItemShow = true">{{areas1}}</text>
										<image class="icon-arrow-green" style="width: 20rpx;height: 20rpx;"></image>进行分析
									</view>
								</u-radio>
								<u-radio key="1" name="Additional.Items.Freely" shape="circle" activeColor="#58C866"
									inactiveColor="#E3E6E9" labelSize="14px" size="16">
									<view>请结合<text
											style="color: #58C866;text-decoration: underline; text-decoration-color: #58C866;"
											@click="assistantItemShow = true">{{areas2}}</text>
										<image class="icon-arrow-green" style="width: 20rpx;height: 20rpx;"></image>自由分析
									</view>
								</u-radio>
							</u-radio-group>
						</view>
						<view
							style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;margin-top: 10px;">
							<u-radio-group v-model="assistant[1].value" placement="column">
								<u-radio key="3" label="需要家园共育建议" name="Additional.Items.FamilyEducation" shape="circle"
									activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-radio>
							</u-radio-group>
						</view>
						<view
							style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;margin-top: 10px;">
							<u-radio-group v-model="assistant[2].value" placement="column">
								<u-radio :customStyle="{marginBottom: '20rpx'}" key="4" label="请写的详细一些"
									name="Content.Length.More" shape="circle" activeColor="#58C866"
									inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-radio>
								<u-radio key="5" label="请写的简略一些" name="Content.Length.Less" shape="circle"
									activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-radio>
							</u-radio-group>
						</view>
						<view
							style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;margin-top: 10px;">
							<u-radio-group v-model="assistant[3].value" placement="column">
								<u-radio :customStyle="{marginBottom: '20rpx'}" key="6" label="请用专业学术的形式书写"
									name="Content.Professional.Expert" shape="circle" activeColor="#58C866"
									inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-radio>
								<u-radio key="7" label="请用给孩子一封信的形式书写" name="Content.Professional.Popular"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
								</u-radio>
							</u-radio-group>
						</view>

					</view>
					<view style="height: 45px; margin: 10px 15px; display: flex; justify-content: space-between;">
						<view class="inline assistant-btn f32">
							<u-button text="取消" @click="assistantPopupShow = false"></u-button>
						</view>
						<view class="inline assistant-btn f32 save">
							<u-button text="确定" @click="handleAssistantSave"></u-button>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		<!-- 选择领域 -->
		<view class="assistant-popup" v-if="assistantItemShow">
			<u-popup :safeAreaInsetBottom="false" :show="assistantItemShow" mode="center"
				@close="assistantItemShow = false">
				<view style="margin-bottom: -10px;">
					<view class="title f32 bold inline">请选择</view>
					<view class="select-cnt">
						<view style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;">
							<u-radio-group v-model="selectAll" placement="column" @change="selectAssistant">
								<u-radio style="font-size: 8px;" key="0" label="相关领域" :name="true" shape="circle"
									activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-radio>
							</u-radio-group>
						</view>

						<view
							style="background-color: #F7F9FA;padding: 10px 10px; border-radius: 6px;margin-top: 10px;">
							<u-checkbox-group v-model="areas" placement="column" @change="selectAssistant">
								<u-checkbox :customStyle="{marginBottom: '30rpx'}" key="1" label="健康" name="健康"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
								</u-checkbox>
								<u-checkbox :customStyle="{marginBottom: '30rpx'}" key="2" label="语言" name="语言"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
								</u-checkbox>
								<u-checkbox :customStyle="{marginBottom: '30rpx'}" key="4" label="科学" name="科学"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
								</u-checkbox>
								<u-checkbox :customStyle="{marginBottom: '30rpx'}" key="3" label="社会" name="社会"
									shape="circle" activeColor="#58C866" inactiveColor="#E3E6E9" labelSize="14px"
									size="16">
								</u-checkbox>
								<u-checkbox key="5" label="艺术" name="艺术" shape="circle" activeColor="#58C866"
									inactiveColor="#E3E6E9" labelSize="14px" size="16">
								</u-checkbox>
							</u-checkbox-group>
						</view>
					</view>
					<view style="height: 45px; margin: 10px 15px; display: flex; justify-content: space-between;">
						<view class="inline assistant-btn f32">
							<u-button text="取消" @click="assistantItemShow = false"></u-button>
						</view>
						<view class="inline assistant-btn f32 save">
							<u-button text="确定" @click="selectAssistantItem"></u-button>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		<view class="popup">
			<!-- 观察地点儿 -->
			<u-picker title="观察的地点" :show="observeOptionsShow" :columns="observeOptionsList" keyName="name"
				@cancel="observeOptionsShow = false" @confirm="locationSelect" cancelColor="#3A3D4B"
				confirmColor="#58C866"></u-picker>
			<!-- 观察环节 -->
			<u-picker :show="showStep" :columns="observeSteps" keyName="name" title="观察的环节" cancelColor="#3A3D4B"
				confirmColor="#58C866" @confirm="stepSelect" @cancel="showStep = false"></u-picker>
		</view>
		<!-- 观察信息录入，确认弹窗 -->
		<rf-alert :show="confirmShow" @close="confirmShow=false" @confirm="confirm" title="提示"
			desc="您还没有填写观察分析与举措，您是希望先保存吗？"></rf-alert>
		<!-- 按次支付观察使用 -->
		<rf-qrAlert :show="showQR" :QRUrl="QRUrl" @close="showQR=false" @confirm="handleAssistantSave"></rf-qrAlert>

		<rf-payAlert :show="android_payConfirmShow" @close="android_payConfirmShow=false" @cancel="onClicktoVip"
			@confirm="android_payConfirm" title="温馨提示" cancelText="成为VIP会员" confirmText="确定缴费">
			<view>您当前还不是超小助VIP会员，此次分析需要<text class="
				red ">{{univalence}}</text>元呦～</view>
		</rf-payAlert>

		<!-- 防止左滑返回， 当showPage值为true的时候阻挡滑动事件（滑动返回或者navback返回的滑动）-->
		<view class="" v-if="showPage">
			<page-container :show="showPage" :overlay="false" @beforeleave="beforeleave('showPage')"></page-container>
		</view>
		<!-- load -->
		<rf-load :loading="loading"></rf-load>
		<!-- 是否将观察，保存为草稿 -->
		<rf-alert :show="draftShow" @close="draftConfirm" @confirm="draftConfirm" title="温馨提示" desc="是否保存为草稿？"
			confirmText="是" cancelText="否"></rf-alert>

		<!-- 获得徽章 -->
		<rf-alertBadge :show="alertBadgeShow" :imageUrl="result.imageUrl" :name="result.name" :remark="result.remark"
			@close="alertBadgeHide"></rf-alertBadge>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState,
	} from 'vuex'; //引入mapState
	import {
		observeList,
		observeAdd,
		observeUp,
		getReleaseAiById,
		createReleaseOrder,
	} from '@/api/observe.js'

	import {
		uploadfile,
		deletefile,
		getObservationLocation,
		getObservationSegment,
		addAiCount,
		getAgreement,
		getServiceQRCode,
		getTeacherInfo,
	} from '@/api/user.js'

	import {
		get
	} from '../../utils/request';
	import {
		Observable,
		from,
		interval,
		throwError,
		timer,
		BehaviorSubject,
	} from 'rxjs';
	import {
		catchError,
		concatMap,
		delay,
		switchMap,
		takeWhile,
		tap,
		map,
		filter,
		take,
	} from 'rxjs/operators';

	export default {
		data() {
			return {
				showPage: true, //一开始设置为显示
				cache: true, // 是否存为草稿，在发布观察后，设置为false
				navBarHeight: this.navBarHeight,
				screenWidth: this.screenWidth,
				screenHeight: this.screenHeight,

				placeholder: "请写出您对孩子行为的分析与相关的教育举措",

				loading: false,

				form: {
					id: "",
					content: '',
					childList: [],
					location: '',
					imageList: [],
					aiAnalysis: '', // ai分析的结果
					areas: [], // 其他领域
					link: '',
					aiAnalysisReq: "", // ai分析的条件
					status: "0", //  ai状态为0：未使用，1:已生成，2:生成中，
				},
				childList: [],
				fileList1: [],
				observerAnalyzeMeasure: '',
				observeOptionsShow: false,
				observeOptionsList: [],
				showStep: false, // 观察环节
				observeSteps: [], // 观察环节，列表
				observeLocations: '',
				observeLink: '',

				aiAssistant: false, // 智能分析中
				timer: null, // 定时器

				savePopupShow: false,
				assistantPopupShow: false,
				assistantItemShow: false,
				assistantSelect: [],
				selectAll: true, // 选择领域，全选
				areas1: "相关领域",
				areas2: "相关领域",
				assistant: [{
						value: 'Additional.Items.WithGuidebook'
					},
					{
						value: 'Additional.Items.FamilyEducation'
					},
					{
						value: 'Content.Length.More'
					},
					{
						value: 'Content.Professional.Expert'
					},
				],
				areasSelestItems: [{
						name: "健康",
						value: "健康"
					},
					{
						name: "语言",
						value: "语言"
					},
					{
						name: "科学",
						value: "科学"
					},
					{
						name: "社会",
						value: "社会"
					},
					{
						name: "艺术",
						value: "艺术"
					},
				],
				areas: [],
				areas1s: [],
				areas2s: [],
				isSus: false,

				dragging: false, // 是否正在拖拽
				mouseX: 0, // 鼠标在元素内的X坐标
				mouseY: 0, // 鼠标在元素内的Y坐标
				left: 0, // 元素左上角距离父容器左侧的距离
				top: 0, // 元素左上角距离父容器顶部的距离

				toast1: false,
				errMsg: "",

				type: "", // 状态用于标识编辑，还是新增观察

				confirmShow: false, // 确认窗口
				showVip: false, // vip 续费弹窗

				univalence: 0.0, // ai分析单次使用费用
				android_payConfirmShow: false,
				systemInfo: {}, //系统信息

				draftShow: false,

				alertBadgeShow: false, // 获取勋章提示
				result: {},

				fileType: "media",

				showQR: false,
				QRUrl: ""
			}
		},
		watch: {
			assistantItemShow(e) {
				this.assistantPopupShow = !e
				console.log(JSON.stringify(this.areas));
			},
			// 'form.content'(newVal, oldVal) {
			// 	console.log(`Name changed from ${oldVal} to ${newVal}`);
			// },
		},
		computed: {
			...mapState(["userInfo"]),
			maxCount() {
				if (this.fileType == "image") {
					return 9
				} else {
					return 1
				}
			},
			mediaType() {
				if (this.fileList1.length <= 0) {
					return "media"
				}
				return this.fileType
			},
			storage() {
				return (this.form.content != "" && this.form.content != null) || (this.form.aiAnalysis != null && this.form
					.aiAnalysis != "")
			}
		},
		created() {
			// 弹出徽章
			this.visibility$ = new BehaviorSubject(this.alertBadgeShow);
			this.visibility$.subscribe(isVisible => {
				this.alertBadgeShow = isVisible;
			});
		},
		onLoad(options) {

			this.left = this.screenWidth - 80;
			this.top = this.screenHeight - 400;
			// 获取系统信息
			this.systemInfo = uni.getSystemInfoSync()

			// 状态用于标识编辑，还是新增观察
			this.type = options.type
			// 如果来自于观察首页的编辑，则填充内容
			if (options.type === "update") {

				const item = JSON.parse(decodeURIComponent(options.item))
				console.log("------------更新------------" + JSON.stringify(item.imagesList));

				this.form.id = item.id
				// 观察实录
				this.form.content = item.content
				// 图片列表
				if (item.imagesList && item.imagesList.length > 0) {
					this.fileList1 = item.imagesList.map((ele) => {
						return {
							url: ele.url
						}
					})
					if (this.isVideoUrl(this.fileList1[0].url)) {
						this.fileType = "video"
					} else {
						this.fileType = "image"
					}
				}
				// ai分析
				this.form.aiAnalysis = item.aiAnalysis
				this.form.status = item.status
				// 观察孩子
				this.childList = item.list ? item.list : []
				// 观察地点儿
				this.form.location = item.location
				// 观察环节
				this.form.link = item.link
			}

			// 获取缓存信息
			var draft = uni.getStorageSync("Obser_draft")
			if (draft && options.type === "create") {
				const item = JSON.parse(draft)

				this.form.id = item.id
				// 观察实录
				this.form.content = item.content
				// 图片列表
				if (item.imagesList) {
					this.fileList1 = item.imagesList
				}

				// ai分析
				this.form.aiAnalysis = item.aiAnalysis
				this.form.status = item.status
				// 观察孩子
				if (item.childList) {
					this.childList = item.childList
				}
				// 观察地点儿
				this.form.location = item.location
				// 观察环节
				this.form.link = item.link
			}
			if (options.type === "create" && options.child && options.child.length > 0) {
				// 通过创建学期评价，跳转过来，填充孩子信息。
				const child = JSON.parse(decodeURIComponent(options.child))
				// 观察孩子
				this.childList.push(child)
			}

			// 获取观察地址，观察环节
			this.getObservationDefault()
			// 获取单次使用ai的费用
			this.get_univalence()

		},
		onShow() {
			// 处理从第二个页面传递过来的参数
			uni.$on('backFromSecondPage', (data) => {
				this.childList = JSON.parse(decodeURIComponent(data))
			});
		},

		methods: {
			...mapMutations(["updateState", "updateUserInfo", "updateBadge"]),
			isVideoUrl(url) {
				// 视频常见后缀名列表
				const videoExtensions = ['mp4', 'flv', 'avi', 'wmv', 'mov', 'mkv', 'rm', 'rmvb'];

				// 获取url的最后一部分（通常为文件名+后缀）
				const fileName = url.split('/').pop();

				// 分离出文件后缀名
				const fileExtension = fileName.split('.').pop().toLowerCase();

				// 判断后缀名是否在视频格式列表中
				return videoExtensions.includes(fileExtension);
			},
			beforeleave() {
				//这个很重要，一定要先把弹框删除掉.
				// 如果拦截完成后，取消还停留在当前页面需要重新设置成 true
				this.showPage = false
				if (this.storage && this.cache) {
					this.draftShow = true;
				} else {
					let pages = getCurrentPages();
					if (pages.length > 1) {
						uni.navigateBack();
					}
				}
			},
			alertBadgeHide() {
				this.visibility$.next(!this.alertBadgeShow);
				// this.alertBadgeShow = false;
				// let pages = getCurrentPages();
				// if (pages.length > 1) {
				// 	uni.navigateBack();
				// }
			},
			selectAssistant(e) {
				console.log("e----------------");
				console.log(e);
				if (e == true) {
					this.areas = []
				}
				if (e.length > 0) {
					console.log(">0");
					this.selectAll = false;
				} else {
					console.log("<=0");
					this.selectAll = true;
				}
			},
			selectAssistantItem() {
				this.assistantItemShow = false;
				console.log(this.assistant[0].value);
				if (this.assistant[0].value == "Additional.Items.WithGuidebook") {
					this.areas1s = this.areas;
					if (this.areas.length > 0) {
						this.areas1 = this.formDataAreas(this.areas);
					} else {
						this.areas1 = "相关领域";
					}
				}

				if (this.assistant[0].value == "Additional.Items.Freely") {
					this.areas2s = this.areas;
					if (this.areas.length > 0) {
						this.areas2 = this.formDataAreas(this.areas);
					} else {
						this.areas2 = "相关领域";
					}
				}

			},
			formDataAreas(arr) {
				var area = []
				for (var i = 0; i < arr.length; i++) {
					for (var m = 0; m < this.areasSelestItems.length; m++) {
						if (this.areasSelestItems[m].value == arr[i]) {
							area.push(this.areasSelestItems[m].name + '领域')
						}
					}
				}
				return area.toString();
			},
			onBack() {
				console.log("OnBack");
				let pages = getCurrentPages();
				if (pages.length > 1) {
					uni.navigateBack();
				}
			},

			draftConfirm(e) {
				// 是否保存为草稿
				if (e) {
					// 临时保存观察草稿
					console.log("缺德鬼");
					// 异步新增本地缓存。

					// this.form.imageList = this.fileList1.map(item => item.url)
					// this.form.childList = this.childList.map(item => item.childId)
					var cacheForm = this.form
					cacheForm.imagesList = this.fileList1
					cacheForm.childList = this.childList
					uni.setStorage({
						key: 'Obser_draft',
						data: JSON.stringify(cacheForm)
					})

				} else {
					// 不保存草稿
					// 清除本地缓存
					uni.removeStorage({
						key: "Obser_draft"
					})
				}

				this.draftShow = false
				// 手动执行返回
				uni.navigateBack({
					delta: 1
				})
			},

			get_univalence() {
				// 获取ai分析单次使用价格
				let _that = this;
				getAgreement(4).then(res => {
					console.log("res: " + JSON.stringify(res));
					console.log(res.data.content);
					_that.univalence = res.data.content
				}).catch(err => {

				})
			},
			showAlertQR() {
				this.loading = true;
				const data = {
					"memberId": "",
					"couponCode": "",
					"type": "1",
				};
				getServiceQRCode(data).then(res => {
					console.log("getServiceQRCode" + JSON.stringify(res));
					if (res.code == 200) {
						this.QRUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + res.data
						this.showQR = true;
					}
					this.loading = false;
				}).catch(err => {
					this.showQR = true;
					this.loading = false;
				})
			},
			onClicktoVip() {
				// 到会员页面成为会员
				uni.navigateTo({
					url: '/pages-sub/Vip/Vip'
				})
			},

			android_payConfirm() {
				let _that = this;
				// 单次使用ai缴费
				if (this.systemInfo.platform === "ios") {
					this.showAlertQR()
				} else {
					from(createReleaseOrder()).pipe(
						// 创建订单
						switchMap(res => {
							// 支付
							return from(_that.createPayment(res.data)).pipe(
								// 延迟两秒
								delay(2000),
								// switchMap(() => {
								// 	// 支付成功，单次AI使用数量加一
								// 	return from(addAiCount())
								// })
							);
						}),
						map(Response => {
							// 加一成功的值 输出
							console.log("Ai 使用次数加一成功后 Response: " + JSON.stringify(Response));
							return Response;
						})
					).subscribe(res => {
						// 订阅单次支付成功结果，直接使用ai助手
						this.handleAssistantSave()
					})
				}
			},
			createPayment(data) {
				let _that = this
				return new Promise((resolve, reject) => {
					uni.requestOrderPayment({
						provider: 'wxpay', //支付类型-固定值
						timeStamp: data.timeStamp.toString(), // 时间戳（单位：秒）
						nonceStr: data.nonceStr, // 随机字符串
						package: data.prepayId, // 固定值
						signType: "RSA", //固定值
						paySign: data.paySign, //签名
						success: function(res) {
							// 支付成功
							resolve(res)
							// 提示支付成功
							uni.showToast({
								title: '支付成功',
								icon: 'success',
								duration: 2000,
								complete() {
									// 提示结束，直接去调用ai分析
								}
							})
						},
						fail: function(err) {
							reject(err)
							console.log('fail:' + JSON.stringify(err));
							// 支付失败，展示支付失败提示
							wx.showToast({
								title: '支付失败',
								icon: 'none'
							})
						}
					})
				});
			},

			// 不等待ai生成结果
			onclickHide() {
				this.aiAssistant = false;
				this.cache = false // 直接返回观察信息不存草稿
				let pages = getCurrentPages()
				if (pages.length >= 1) {
					uni.navigateBack()
				}
			},
			getObservationDefault() {
				let _that = this
				getObservationLocation().then(res => {
					console.log("观察地址: " + JSON.stringify(res));

					_that.observeOptionsList.push(res.data)
				})
				getObservationSegment().then(res => {

					console.log("观察环节: " + JSON.stringify(res));
					_that.observeSteps.push(res.data)
				})
			},
			// --观察步骤选择---------------------------------------------
			stepSelect(e) {
				this.showStep = false
				this.form.link = e.value[0].name;
				// this.form.position = e.value[0].id;
				// this.position = e.value[0].name;
			},
			// 观察地点儿选择
			locationSelect(e) {
				this.observeOptionsShow = false
				this.observeLocations = e.value[0].id;
				this.form.location = e.value[0].name
			},

			assistantShowOpen() {
				let _that = this;

				// 会员有效后续操作
				if (!this.form.content) {
					console.log("-=--=-=--=-");
					this.errMsg = "请填写观察实录"
					this.toast1 = true
					// uni.showToast({
					// 	title: '请填写观察实录'
					// })
					return
				}
				if (this.form.content.length < 10) {
					uni.showToast({
						icon: "none",
						title: "输入字数不能少于10个字～",
						duration: 2000
					})
					return
				}
				if (this.childList.length <= 0) {
					this.errMsg = "请选择观察的孩子"
					this.toast1 = true
					// uni.showToast({
					// 	title: '请选择观察的孩子',
					// })
					return
				}
				// 弹出ai 分析选项
				this.assistantPopupShow = true;

			},

			// 删除图片
			deletePic(event) {
				let item = this[`fileList${event.name}`][event.index]

				const data = {
					"path": item.url
				};
				console.log("data: " + JSON.stringify(data));
				deletefile(data).then(res => {

				}).catch(err => {
					console.log(err);
				})

				this[`fileList${event.name}`].splice(event.index, 1)

			},
			// 新增图片
			async afterRead(event) {
				console.log(event);
				console.log(JSON.stringify(event));
				// {"file":[{"fileType":"image","size":913703,"tempFilePath":"wxfile://tmp_dda1f8c57b788488331b432315338499.jpg"}],"name":"1","index":0}
				console.log("-------------afterRead-----------------");
				if (event.file[0].type == "video") {
					this.fileType = "video"
				} else {
					this.fileType = "image"
				}
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return uploadfile(url)
			},
			// 观察的孩子
			handleObserveChild() {
				const childList = this.childList ? encodeURIComponent(JSON.stringify(this.childList)) : []
				uni.navigateTo({
					url: '/pages-sub/observeAdd/obsereveChild?childList=' + childList
				});
			},
			// 观察的地点
			handleObserveLocations() {
				this.observeOptionsShow = true;
			},
			// 观察的环节
			handleObserveLink() {
				this.showStep = true;
			},
			// 观察内容校验
			handleSave() {

				if (!this.form.content) {
					console.log("-=--=-=--=-");
					this.errMsg = "请填写观察实录"
					this.toast1 = true
					return
				}
				if (this.form.content.length < 10) {
					uni.showToast({
						icon: "none",
						title: "输入字数不能少于10个字～",
						duration: 2000
					})
					return
				}
				if (this.childList.length <= 0) {
					this.errMsg = "请选择观察的孩子"
					this.toast1 = true
					// uni.showToast({
					// 	title: '请选择观察的孩子',
					// })
					return
				}

				if (this.form.aiAnalysis == null || this.form.aiAnalysis == "") {
					// 您还没有填写观察分析与举措，您是希望先保存吗？
					this.confirmShow = true
					return
				}
				this.saveObserve()
			},

			confirm() {
				// 保存观察
				this.confirmShow = false
				this.saveObserve()
			},
			async saveObserve() {
				// 保存观察，不使用ai小助手

				// 正在提交观察
				this.loading = true

				uni.removeStorage({
					key: "Obser_draft"
				})
				// 创建观察直接保存
				console.log(this.fileList1);
				console.log(this.childList);
				this.form.imageList = this.fileList1.map(item => item.url)
				this.form.childList = this.childList.map(item => item.childId)
				// this.form.aiAnalysisReq = this.assistantSelect
				this.form.aiAnalysisReq = []
				// if (this.assistantSelect.length > 0) {
				// 	// 选择了ai分析参数，提示ai生成
				// 	this.aiAssistant = true;
				// }

				console.log("res: " + JSON.stringify(this.form));
				if (this.type == "update") {
					// 更新观察
					from(observeUp(this.form)).pipe(
						tap(response => {
							if (response.code === 200) {
								// 更新成功后不需要保存草稿
								this.cache = false;
								this.loading = false;
								console.log('更新成功后不需要保存草稿');
								uni.navigateBack()
							} else if (response.statusCode === 6001) {
								// 不能使用ai分析助手，弹出请缴费
								this.android_payConfirmShow = true;
								console.log('不能使用ai分析助手，弹出请缴费');
							} else if (response.statusCode >= 500) {
								console.log('Server Error: There seems to be an issue on the server side.');
							}
						}),
						catchError(error => {

						}),
						// switchMap(data => {
						// 	return
						// })
					).subscribe(res => {
						console.log(JSON.stringify(res));
						console.log("-------------------------------");
					})

				} else {
					// 创建观察
					from(observeAdd(this.form)).pipe(
						tap(response => {
							if (response.code === 200) {
								// 发布过的观察信息均不需要存草稿
								this.cache = false
								this.loading = false
								if (this.assistantSelect.length <= 0) {
									this.isSus = true;
									this.savePopupShow = true;
								}
								setTimeout(() => {
									// this.aiAssistant = false;
									this.savePopupShow = false;
									if (response.data.isBadge == 1) {
										// 提示获得徽章
										this.visibility$.next(!this.alertBadgeShow);
										this.result = response.data;
										this.visibility$.pipe(
											filter(isVisible => !isVisible)
										).subscribe(() => {
											let pages = getCurrentPages();
											if (pages.length > 1) {
												uni.navigateBack();
											}
										})

									} else {
										this.cache = false
										let pages = getCurrentPages();
										if (pages.length > 1) {
											uni.navigateBack();
										}
									}
								}, 1500)
							} else if (response.statusCode === 6001) {
								// 不能使用ai分析助手，弹出请缴费
								this.android_payConfirmShow = true;
								console.log('不能使用ai分析助手，弹出请缴费');
							} else if (response.statusCode === 500) {
								this.isSus = false;
								this.savePopupShow = true;
							}
						}),

					).subscribe(res => {
						console.log("=========创建观察===========");
						console.log(JSON.stringify(res));
					})

				}
			},
			// 超级助教选择事件
			handleAssistant(even) {

				console.log(even)
				if (even == "Additional.Items.WithGuidebook") {
					this.form.areas = this.areas;
				}

			},

			getReleaseSignal(formid, resp) {
				let _that = this
				return interval(2000).pipe(
					concatMap(() => {
						if (formid) {
							// 更新观察
							console.log("------更新-----" + resp.data)
							return from(getReleaseAiById(resp.data))
						} else {
							console.log("------获取-----" + resp.data.releaseId)
							return from(getReleaseAiById(resp.data.releaseId))
						}
					}),
					takeWhile((result) => {
						if (result.data.status == 1) {
							// ai分析完成

							_that.aiAssistant = false;

							// 返回首页
							_that.cache = false
							uni.navigateBack()

							//停止轮询请求
							return false
						}
						return true
					})
				)
			},

			// 调用ai助手之前，获取会员信息
			beforeUsingAssistant() {},
			// 超级助教保存
			handleAssistantSave() {
				let _that = this;
				// 使用ai小助手

				// 组装数据
				this.assistantPopupShow = false;
				this.assistantSelect = this.assistant.map(item => {
					return item.value
				})
				this.form.imageList = this.fileList1.map(item => item.url)
				// ai分析选项
				this.form.aiAnalysisReq = this.assistantSelect
				// 选择领域

				if (this.assistant[0].value == "Additional.Items.WithGuidebook") {
					this.form.areas = this.areas1s;
				}

				if (this.assistant[0].value == "Additional.Items.Freely") {
					this.form.areas = this.areas2s;
				}

				// 孩子列表
				this.form.childList = this.childList.map(item => item.childId)
				console.log(JSON.stringify(this.form));

				_that.form.status = "2" // 默认为生成中
				console.log("_that.form: " + JSON.stringify(_that.form));

				// 现获取会员信息
				// 获取一次用户信息, 会员是否有效
				// 发起请求
				from(getTeacherInfo()).pipe(
					tap(res => {
						_that.updateUserInfo(res.data)
					}),
					filter(res => {
						if (this.userInfo.memberType === 0 && this.userInfo.aiUseCount <= 0) {
							// 没有会员权限
							// 弹出加入会员
							this.android_payConfirmShow = true;
							return false
						} else {
							// 有会员权限
							// 显示ai分析loading
							this.aiAssistant = true;
							// 继续信号流
							return true
						}
					}),
					switchMap(res => {
						if (_that.form.id) {
							// 更新观察的接口只返回一个观察消息的ID值
							return this.updataObseveInfo()
						} else {
							return this.createObseveInfo()
						}
					})
				).subscribe({
					next: (res) => {
						console.log('观察创建或更新结束:', res)
					},
					error: (err) => console.error('观察创建或更新失败:', err),
					complete: () => {
						// 取消loading
						// this.aiAssistant = false;
					}
				})

			},
			/** 创建观察 */
			createObseveInfo() {
				let _that = this
				// 新增操作可以产生徽章
				var source = from(observeAdd(this.form))

				source.pipe(
					filter(response => response.data.isBadge === 1), // 有徽章
					switchMap((data) => {
						// 显示徽章
						this.visibility$.next(!this.alertBadgeShow);
						this.result = data.data;
						return this.visibility$.pipe(
							filter(isVisible => !isVisible),
							switchMap(() => {
								return _that.getReleaseSignal(_that.form.id, data)
							})
						)
					}),
				).subscribe(res => {
					console.log("观察创建成功，有徽章" + res);
				})

				source.pipe(
					filter(response => response.data.isBadge === 0), // 没有徽章
					switchMap((data) => {
						return _that.getReleaseSignal(_that.form.id, data)
					}),
				).subscribe(res => {
					console.log("观察创建成功，无徽章" + res);
				})
				return source
			},
			/** 
			 * 更新观察 
			 */
			updataObseveInfo() {

				let _that = this
				// 更新操作没有徽章
				var source = from(observeUp(this.form))
				// 更新观察的接口只返回一个观察消息的ID值
				source.pipe(
					filter(response => response.code === 200), // 更新成功
					switchMap((data) => {
						return _that.getReleaseSignal(_that.form.id, data)
					}),
				).subscribe(res => {
					console.log("更新完成，获取到ai数据" + res);
				})
				return source
			},
			handleMouseDown(event) {
				this.dragging = true;
				this.mouseX = event.changedTouches[0].clientX;
				this.mouseY = event.changedTouches[0].clientY;
			},
			handleMouseMove(event) {
				if (this.dragging) {
					console.log("event", event);
					console.log("screenWidth", this.screenWidth);
					console.log("screenHeight", this.screenHeight);
					const deltaX = event.changedTouches[0].clientX - this.mouseX;
					const deltaY = event.changedTouches[0].clientY - this.mouseY;

					var left = this.left + deltaX;
					var top = this.top + deltaY;
					if (left <= 0) {
						this.left = 0
					} else if (left >= (this.screenWidth - 70)) {
						this.left = (this.screenWidth - 70)
					} else {
						this.left = left;
					}
					if (top <= 0) {
						this.top = 0
					} else if (top >= (this.screenHeight - 70)) {
						this.top = (this.screenHeight - 70)
					} else {
						this.top = top;
					}
					this.mouseX = event.changedTouches[0].clientX;
					this.mouseY = event.changedTouches[0].clientY;
				}
			},
			handleMouseUp(event) {
				this.dragging = false;
			},
		}
	}
</script>

<style lang="scss">
	page {
		position: relative !important;
		top: 0px !important;
	}

	.add-observe {

		.header {
			position: relative;


			.bg {
				width: 100%;
				height: 64px;
				// height: 367rpx;
				position: fixed;
				z-index: 998;
				left: 0;
				top: 0;
			}

			.bg-bottom {
				position: fixed;
				left: 0;
				top: 64px;
				z-index: -1;
				width: 100vh;

				// height: 300px;
				// height: 367rpx;



			}
		}

		.body {
			position: relative;
			top: -30rpx;
			z-index: 991;
			padding: 40rpx 40rpx 190rpx 40rpx;

			.title {
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: rgba(0, 0, 0, 0.85);
				line-height: 40rpx;
				text-align: left;
				font-style: normal;
			}

			.observe-memoir-input,
			.observe-analyze-measure-input {
				min-height: 150rpx;
				width: 100%;
				height: auto;
				// background: #F4F7F9;
				border-radius: 20rpx;

				font-size: 28rpx;
				// line-height: 40rpx;
				letter-spacing: 3rpx;

				margin-left: -20rpx;
				margin-right: -20rpx;

				::v-deep.u-textarea__field {
					min-height: 100rpx;
					// height: auto;
					// height: auto !important;
					// color: red;
				}
			}

			::v-deep .input-placeholder {
				// color: #b2b2b2 !important;
				font-size: 28rpx;
				// line-height: 30rpx;
				height: 100rpx !important;

				width: 100rpx !important;
			}

			.u-textarea--radius {
				border: none;
				background-color: transparent;
			}

			.u-textarea__field {
				font-size: 28rpx;
				font-weight: 400;
				// color: #000000;
				color: #3A3D4B;
			}

			.create-wrap {
				display: flex;
				align-items: center;
				margin-top: 60rpx;
				margin-bottom: 60rpx;

				.observe-assistant {
					flex: 2;
					height: 88rpx;
					background-color: #FFA930;
					border-radius: 44rpx;
					display: flex;
					justify-content: center;
					align-items: center;

					.icon {
						width: 29px;
						height: 29px;
					}

					text {
						font-size: 16px;
						font-family: PingFangSC, PingFang SC;
						font-weight: 600;
						color: #FFFFFF;
						line-height: 22px;
					}
				}

				.save-btn {
					flex: 1;
					margin-left: 10px;

					.u-button--square {
						height: 88rpx;
						border: none;
						border-radius: 44rpx;
						background-color: #58C866;
					}

					.u-button__text {
						font-size: 16px;
						font-weight: bold;
						color: #fff;
					}
				}

			}



			.observe-details-list {
				width: 650rpx;
				height: 90rpx;
				line-height: 90rpx;
				border-bottom: 1rpx solid #EBECED;
				color: #273344;

				.icon {
					width: 32rpx;
					height: 32rpx;
					vertical-align: middle;
				}

				.text {
					margin-left: 14rpx;
				}
			}

			.observe-child {
				margin-top: 30rpx;
			}




			.headImg {
				display: flex;
				justify-content: flex-end;
				align-items: center;
				flex: 1;
				height: 90rpx;
				position: relative;

				.image {
					width: 60rpx;
					height: 60rpx;
					margin: 0 5rpx;
					border-radius: 50%;
					position: relative;
				}

				.image:nth-child(5)::after {
					content: "•••";
					right: 0;
					position: absolute;
					text-align: center;
					line-height: 60rpx;
					top: 0;
					z-index: 99;
					display: inline-block;
					color: #fff;
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					background-color: rgba(0, 0, 0, 0.3);
				}

				.mask {
					position: absolute;
					top: 0;
					left: 0;
					background-color: rgba(0, 0, 0, 0.6);
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					z-index: 999;
				}
			}
		}

		// .save-popup {
		// 	.u-popup__content.data-v-3a231fda {
		// 		width: 480rpx;
		// 		height: 332rpx;
		// 		border-radius: 20rpx;

		// 		.success-icon {
		// 			display: block;
		// 			width: 128rpx;
		// 			height: 128rpx;
		// 			margin: 48rpx auto 0;
		// 		}

		// 		.success-tips {
		// 			display: block;
		// 			text-align: center;
		// 			margin-top: 10rpx;
		// 		}

		// 		.success-text {
		// 			display: block;
		// 			text-align: center;
		// 			color: #77798D;
		// 			margin-top: 10rpx;
		// 		}

		// 		.u-icon__icon.data-v-2ee87dc9 {
		// 			color: #3d3d3d;
		// 		}
		// 	}
		// }



		.assistant-popup {
			.u-popup__content {
				width: 600rpx;
				// height: 650rpx;
				border-radius: 20rpx;
				border: 12rpx solid #F4F8F7;

				.assistant-icon {
					width: 226rpx;
					height: 322rpx;
					position: absolute;
					right: -12rpx;
					top: -194rpx;
				}

				.title {
					line-height: 22rpx;
					border-bottom: 12rpx solid rgba(88, 200, 102, .55);
					box-sizing: border-box;
					margin-top: 40rpx;
					margin-left: 28rpx;
				}

				.data-v-c4a74aee {
					font-size: 28rpx !important;
					color: #3A3D4B;
				}

				.u-checkbox__icon-wrap--circle {
					width: 32rpx !important;
					height: 32rpx !important;
				}

				.select-cnt {
					padding: 35rpx 28rpx 0;
				}

				.assistant-btn {
					width: 244rpx;
					height: 72rpx;

					.u-button--square {
						border-radius: 44rpx;
						background-color: #F2F3F7;
						color: #3A3D4B;
						border: none;
					}

					&.save {
						.u-button--square {
							background-color: #58C866;
							color: #FFF;
						}
					}
				}
			}
		}

		.popup {
			.u-popup__content {
				position: relative;
				border-radius: 24rpx 24rpx 0 0;
				overflow: hidden;
				padding-bottom: 150rpx;
			}

			.u-picker__view {
				height: 360rpx !important;
			}


			.u-toolbar__wrapper__cancel {
				padding: 0;
				position: absolute;
				left: 100rpx;
				bottom: -78rpx;

				width: 200rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.u-toolbar__wrapper__confirm {
				padding: 0;
				position: absolute;
				right: 100rpx;
				bottom: -78rpx;

				width: 200rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

	}
</style>